package com.ss.whisper2.service.impl;

import com.ss.whisper2.dao.CourseDao;
import com.ss.whisper2.exception.GlobalException;
import com.ss.whisper2.pojo.State;
import com.ss.whisper2.pojo.entity.course.Course;
import com.ss.whisper2.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {

	private static final int DEFAULT_MAX_RETRIES = 5;

	@Autowired
	CourseDao courseDao;

	@Override
	@Transactional(isolation=Isolation.REPEATABLE_READ,timeout = 1)
	public List<Course> getAllCourses() {
		return courseDao.getAllCourses();
	}


	//@Cacheable("selected-course")
	@Override
	public List<Course> getSelectedCourses(String username) {
		List<Integer> courseIds= courseDao.getCourseIdByUserName(username);
		List<Course> selectedCourses = new ArrayList<>();
		for (int i : courseIds) {
			selectedCourses.add(courseDao.getCourseById(i));
		}
		return selectedCourses;
	}

	@Transactional(isolation=Isolation.REPEATABLE_READ)
	//@Async
	@Override
	public void selectCourse(String username, Integer courseId){
		int attempt = 0, result = 0;
		do {
			attempt++;
			courseDao.selectCourse(username, courseId);
			result = courseDao.decrCourse(courseId, courseDao.getVersion(courseId));
			if (result==1)
				break;
		} while (attempt < DEFAULT_MAX_RETRIES);
	}

	@Override
	public int getCourseRest(Integer courseId) {
		return courseDao.getCourseRest(courseId);
	}

	@Override
	public boolean getSelectedCourseResult(String username, Integer courseId) {
		return courseDao.getSelectCourseResult(username, courseId)==1;
	}

	@Override
	public List<Integer> getScoreList(String username) {
		return courseDao.getScoreList(username);
	}

	@Override
	public List<Integer> getBehaveScoreList(String username) {
		return courseDao.getBehaveScoreList(username);
	}

	@Override
	public List<Integer> getLastScoreList(String username) {
		return courseDao.getLastScoreList(username);
	}

	@Override
	public List<Integer> getExperimentScoreList(String username) {
		return courseDao.getExperimentScoreList(username);
	}
}
